package utils;

import gui.ChatWin;

import java.io.IOException;
import java.io.PipedInputStream;
import java.util.StringTokenizer;

import javax.swing.JInternalFrame;

import org.apache.log4j.Logger;

import connection.Reader;

/**
 * Rozpoznava jestli se jedna o chat zpravu a urcuje kam patri
 * 
 * @author dove
 * 
 */
public class ChatParser implements Runnable {

	private ChatWin chat;
	private PipedInputStream br;
	private boolean running;
	private String word = "";
	private static Logger logger = Logger.getLogger("Log");
	private Thread chatThread = null;
	private int letter;
	private String lastMessage = "Shouts";

	/**
	 * Inicializace a vytvari chatovaci okno do GUI
	 */
	public ChatParser(ChatWin chat) {
		this.chat = chat;
		br = Reader.getReader("Chat");
		running = true;
		chatThread = new Thread(this);
		chatThread.start();
	}

	/**
	 * Vraci chatovaci okno do GUI
	 * 
	 * @return JInternalFrame okno v GUI
	 */
	public JInternalFrame getWindow() {
		return chat.getWindow();
	}

	/**
	 * Zjisteni kanalu kam zprava patri
	 * 
	 * @param message
	 *            zprava z chatu
	 * @return cislo kanalu zpravy
	 */
	public String getChannel(String message) {
		if (message.substring(message.length() - 5, message.length() - 4)
				.equals("(")) {
			return message
					.substring(message.length() - 4, message.length() - 2);
		} else if (message
				.substring(message.length() - 6, message.length() - 5).equals(
						"(")) {
			return message
					.substring(message.length() - 5, message.length() - 2);
		} else {
			return message
					.substring(message.length() - 3, message.length() - 2);
		}
	}

	/**
	 * Zjistuje jestli je jde o chat zpravu
	 * 
	 * @param message
	 *            radek prijaty ze serveru
	 * @return jestli se jedna o zpravu
	 */
	public boolean isMessage(String message) {
		String pom = "";
		StringTokenizer token = new StringTokenizer(message);
		if (token.hasMoreTokens()) {
			pom = token.nextToken();
		}

		// Dranok(1): ah... that was simple
		if (pom.length() > 2) {
			if (pom.substring(pom.length() - 2, pom.length()).equals("):")) {
				chat.addText(message, getChannel(pom));
				lastMessage = getChannel(pom);
				return true;
			}
		}
		if (pom.equals("**ANNOUNCEMENT**")) {
			chat.addText(message, "Shouts");
			lastMessage = "Shouts";
			return true;
		}
		if (token.hasMoreTokens()) {
			pom = token.nextToken();
		}
		// mamer(TD) c-shouts: Interested in playing some tournam
		if (pom.length() > 6) {
			if (pom.substring(pom.length() - 7, pom.length()).equals("shouts:")) {
				chat.addText(message, "Shouts");
				lastMessage = "Shouts";
				return true;
			}
		}
		// Actionable says: gg
		// Actionable[28] says: hey

		// GuestNFVQ(U)[185] says: Hello
		if (pom.equals("says:")) {
			chat.addText(message, "Game");
			lastMessage = "Game";
			return true;
		}

		if (token.hasMoreTokens()) {
			pom = token.nextToken();
		}

		// Actionable tells you: .....
		if (pom.equals("you:")) {
			chat.addText(message, "Game");
			lastMessage = "Game";
			return true;
		}
		return false;
	}

	public void run() {

		Reader.setReading("Chat");

		while (running) {
			word = "";
			if (letter == 13) {
				try {
					letter = br.read();
				} catch (Exception e) {
					logger.error("", e);
				}
				word = word.concat(String.valueOf((char) letter));
			}
			while (letter != 13) {
				if (!Reader.isConnect()) {
					running = false;
				}
				try {
					if (Reader.isConnect()) {
						letter = br.read();
					} else {
						return;
					}
				} catch (Exception e) {
					logger.error("", e);
				}
				word = word.concat(String.valueOf((char) letter));
				if (word.equals("****")) {
					Reader.sendString("=channel");
					logger.debug("channel");
					letter = 13;
					word = "";
				}
				if (word.equals("fics% -- channel list:")) {
					while (letter != 13) {
						try {
							letter = br.read();
						} catch (IOException e) {
							logger.error("", e);
						}
					}
					word = "";
					do {
						try {
							letter = br.read();
						} catch (IOException e) {
							logger.error("", e);
						}
						word = word.concat(String.valueOf((char) letter));
					} while (letter != 13);
					StringTokenizer chan = new StringTokenizer(word);
					while (chan.hasMoreTokens()) {
						chat.addChannel(chan.nextToken());
					}
				}
			}
			String a = "\\";
			if (word.length() > 0) {
				if (word.substring(0, 1).equals(a)) {
					chat.addText(word, lastMessage);
				}
			}
			if (isMessage(word)) {
				logger.debug("JE ZPRAVA:" + word);
			}
		}
	}
}
